<template>
  <div class="header-bar">
    <el-button
        plain
        type="info"
        icon="ArrowLeft"
        @click="handleBack"
        class="back-btn"
    >
      返回
    </el-button>
    <h2 class="page-title">用户资讯管理</h2>
  </div>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['healthSys:info:add']"
            class="add-btn"
        >新增</el-button>
      </el-form-item>
      <el-form-item label="资讯标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入资讯标题"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资讯类型" prop="infoType">
        <el-select v-model="queryParams.infoType" placeholder="请选择资讯类型" clearable style="width: 100px;">
          <el-option
              v-for="dict in info_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布状态" prop="status"  clearable style="width: 200px">
        <el-select v-model="queryParams.status" placeholder="请选择发布状态" clearable>
          <el-option
              v-for="dict in publish_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="资讯标题" align="center" prop="title" />
      <el-table-column label="资讯作者" align="center" prop="userName" />
      <el-table-column label="资讯内容"  align="center" :min-width="120" class-name="content-column">
        <template #default="scope">
          <div class="content-wrapper">
            <el-tooltip
                effect="dark"
                :content="cleanHtml(scope.row.content)"
                placement="top-start"
                :disabled="!scope.row.content"
            >
              <div class="content-text">
                {{ cleanHtml(scope.row.content) || '-' }}
              </div>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="封面" align="center" prop="coverImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.coverImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="资讯类型" align="center" prop="infoType">
        <template #default="scope">
          <dict-tag :options="info_type" :value="scope.row.infoType"/>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="categoryId">
        <template #default="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column label="发布状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="publish_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="publishTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="点赞数" align="center" prop="likeCount" width="100">
        <template #default="scope">
          <span>{{ scope.row.likeCount || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改资讯管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="infoRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="资讯标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入资讯标题" />
        </el-form-item>
        <el-form-item label="资讯内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="封面图" prop="coverImg">
          <image-upload v-model="form.coverImg"/>
        </el-form-item>
        <el-form-item label="资讯类型" prop="infoType">
          <el-select v-model="form.infoType" placeholder="请选择资讯类型">
            <el-option
                v-for="dict in info_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select
              v-model="form.categoryId"
              placeholder="请选择分类"
              filterable
              clearable
          >
            <el-option
                v-for="item in categoryList"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择发布状态">
            <el-option
                v-for="dict in publish_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="记录日期" prop="publishTime">
          <el-date-picker
              v-model="form.publishTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
              :disabled-date="disabledDate"
              class="w-full"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script setup name="Info">
import { listhealthInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/healthSys/info";
import { listCategory } from "@/api/healthSys/category";
import { getLikeCount } from "@/api/healthSys/like";
import { useRouter } from 'vue-router'
import { useDict } from "@/utils/dict";

const router = useRouter()

const { proxy } = getCurrentInstance();
const { info_type, publish_status } = useDict('info_type', 'publish_status');

// 添加 cleanHtml 工具函数
function cleanHtml(html) {
  const doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent || "";
}

const infoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    infoType: null,
    categoryId: null,
    status: null,
  },
  rules: {
    title: [
      { required: true, message: "资讯标题不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "资讯内容不能为空", trigger: "blur" }
    ],
    infoType: [
      { required: true, message: "资讯类型不能为空", trigger: "change" }
    ],
    categoryId: [
      { required: true, message: "分类不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "发布状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
const handleBack = () => {
  router.go(-1)
}

/** 查询资讯管理列表 */
function getList() {
  loading.value = true;
  listhealthInfo(queryParams.value).then(response => {
    infoList.value = response.rows;
    total.value = response.total;
    // 获取每个资讯的点赞数
    infoList.value.forEach(info => {
      getLikeCount(info.infoId).then(res => {
        info.likeCount = res.data;
      });
    });
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

const disabledDate = (time) => {
  return time.getTime() > Date.now()
}
// 表单重置
function reset() {
  form.value = {
    infoId: null,
    title: null,
    content: null,
    coverImg: null,
    infoType: null,
    categoryId: null,
    status: null,
    publishTime: null,
    remark: null
  };
  proxy.resetForm("infoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.infoId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "发布资讯";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _infoId = row.infoId || ids.value
  getInfo(_infoId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改资讯";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["infoRef"].validate(valid => {
    if (valid) {
      if (form.value.infoId != null) {
        updateInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _infoIds = row.infoId || ids.value;
  proxy.$modal.confirm('是否确认删除资讯管理编号为"' + _infoIds + '"的数据项？').then(function() {
    return delInfo(_infoIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('healthSys/info/export', {
    ...queryParams.value
  }, `info_${new Date().getTime()}.xlsx`)
}
// 获得分类列表
const categoryList = ref([]);
function getCategoryList() {
  listCategory().then(response => {
    categoryList.value = response.rows;
  }).catch(error => {
    proxy.$modal.msgError("分类加载失败");
  });
}
function getCategoryName(categoryId) {
  const category = categoryList.value.find(item => item.categoryId === categoryId);
  return category ? category.categoryName : '未知分类';
}
getCategoryName();
getCategoryList();
getList();

/** 查看按钮操作 */
function handleView(row) {
  const _infoId = row.infoId || ids.value[0];
  getInfo(_infoId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "查看资讯详情";
  });
}

/** 批量编辑按钮操作 */
function handleBatchEdit() {
  if (ids.value.length === 0) {
    proxy.$modal.msgError("请选择要编辑的资讯");
    return;
  }
  reset();
  open.value = true;
  title.value = "批量编辑资讯";
}
</script>
<style scoped>
.app-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.header-bar {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(28, 36, 56, 0.08);
  transition: all 0.3s ease;
}

.header-bar:hover {
  box-shadow: 0 6px 20px rgba(28, 36, 56, 0.12);
}

.back-btn {
  margin-right: 24px;
  padding: 10px 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.back-btn:hover {
  transform: translateX(-3px);
  background-color: #f5f7fa;
}

.add-btn {
  background-color: #409EFF;
  color: #ffffff;
  margin-right: 16px;
  padding: 8px 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.add-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.page-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #1a1a1a;
  letter-spacing: 0.5px;
  position: relative;
  padding-left: 16px;
}


.mb8 {
  margin-bottom: 20px;
  background: #ffffff;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(28, 36, 56, 0.06);
}

.el-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(28, 36, 56, 0.06);
  margin-top: 16px;
  border: none;
}

.el-table::before {
  display: none;
}

.el-table th {
  background-color: #f5f7fa !important;
  font-weight: 600;
  color: #1a1a1a;
  padding: 16px 0;
  border-bottom: 2px solid #ebeef5;
  font-size: 14px;
}

.el-table td {
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
  font-size: 14px;
}

.el-table__row {
  transition: all 0.3s ease;
}

.el-table__row:hover {
  background-color: #f5f7fa !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(28, 36, 56, 0.08);
}

.el-table__row:hover td {
  background-color: transparent !important;
}

/* 表格内容样式优化 */
.content-column .cell {
  max-height: 60px;
  padding: 0 16px;
}

.content-wrapper {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.6;
  max-height: 60px;
  padding: 8px 0;
}

.content-text {
  word-break: break-word;
  color: #606266;
  font-size: 13px;
}

/* 表格操作列样式 */
.el-table .operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
}

.el-table .operation-btn {
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
}

.el-table .operation-btn:hover {
  background-color: #f5f7fa;
  transform: translateY(-1px);
}

.el-table .operation-btn[type="primary"] {
  color: #409EFF;
}

.el-table .operation-btn[type="primary"]:hover {
  background-color: #ecf5ff;
  color: #409EFF;
}

.el-table .operation-btn[type="danger"] {
  color: #f56c6c;
}

.el-table .operation-btn[type="danger"]:hover {
  background-color: #fef0f0;
  color: #f56c6c;
}

/* 表格选择列样式 */
.el-table .el-table-column--selection .cell {
  padding: 0 16px;
}

/* 表格图片预览样式 */
.el-table .image-preview {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(28, 36, 56, 0.08);
  transition: all 0.3s ease;
}

.el-table .image-preview:hover {
  transform: scale(1.05);
}

/* 表格状态标签样式 */
.el-table .el-tag {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
  font-size: 12px;
}

/* 表格分页样式优化 */
.el-pagination {
  margin-top: 24px;
  justify-content: flex-end;
  padding: 16px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(28, 36, 56, 0.06);
}

.el-pagination .el-pagination__total {
  margin-right: 16px;
}

.el-pagination .el-pagination__sizes {
  margin-right: 16px;
}

.el-pagination .el-pagination__jump {
  margin-left: 16px;
}

.el-pagination .el-pagination__total,
.el-pagination .el-pagination__sizes,
.el-pagination .el-pagination__jump {
  color: #606266;
  font-size: 14px;
}

.el-pagination .el-pagination__total .el-input__wrapper {
  box-shadow: none;
  background-color: #f5f7fa;
}

.el-pagination .el-pagination__total .el-input__inner {
  text-align: center;
  color: #606266;
}

.el-pagination .el-pagination__total .el-input__inner:hover {
  color: #409EFF;
}
</style>
